package com.telecomyt.jwportal.http.gson;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * @author VurtneWk
 * 2018/6/4.
 */
public class CustomResponseConverter<T> implements Converter<ResponseBody, T> {

    private final Gson gson;
    private final TypeAdapter<T> adapter;

    CustomResponseConverter(Gson gson, TypeAdapter<T> adapter) {
        this.gson = gson;
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String originalBody = value.string();
        try {
            JSONObject json = new JSONObject(originalBody);
            int code = json.optInt("code");
            if (code == 2 || code == 0) {
                /*AppUtils.loginOut(Utils.getContext());
                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setClass(Utils.getContext(), LoginActivity.class);
                Utils.getContext().startActivity(intent);*/
            }
            if (code != 1) {
                String msg = json.optString("msg");
                if (!TextUtils.isEmpty(msg)) {
//                    ToastUtils.showShortSafe(msg);
                }
            }
            return adapter.fromJson(originalBody);
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        } finally {
            value.close();
        }
    }

}

